package com.sakura.二叉树;

import java.util.ArrayDeque;
import java.util.Deque;

public class Code513_找树左下角的值 {
    
      // Definition for a binary tree node.
      public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    // 层序遍历，从右遍历到左，那么最后的就是最左边的节点
    public int findBottomLeftValue(TreeNode root) {
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            while (size-- > 0) {
                root = queue.poll();
                if (root.right != null ) {
                    queue.offer(root.right);
                }
                if (root.left != null) {
                    queue.offer(root.left);
                }
            }
        }
        return root.val;
    }
}
